package day01;

public class DynamicArray<T> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;//元素个数
    private Object[] elementData;

    public DynamicArray() {
        this.size = 0;
        elementData = new Object[DEFAULT_CAPACITY];
    }

    private void ensureCapacity(int mainCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity < mainCapacity) {
            Object[] newEelementData = new Object[2 * oldCapacity];
            System.arraycopy(elementData, 0, newEelementData, 0, oldCapacity);
            elementData = newEelementData;
        }
    }

    public void add(T element) {
        ensureCapacity(this.size + 1);
        this.elementData[this.size] = element;
        this.size++;
    }

    public T get(int index) {
        if (index < 0 || index >= this.size) {
            throw new IndexOutOfBoundsException();
        }// 将Object类型强制转换为泛型T类型
        return (T) this.elementData[index];
    }

    public int size() {
        return this.size;
    }

    public void set(int index, T element) {
        if (index < 0 || index >= this.size) {
            throw new IndexOutOfBoundsException();
        }
        this.elementData[index] = element;
    }

    public <E extends T> void addAll(DynamicArray<E> c) {
        for (int i = 0; i < c.size; i++) {
            add(c.get(i));
        }
    }

    public static <T> void swap(DynamicArray<T> array, int i, int j) {
        if (i >= array.size() || j >= array.size() || i < 0 || j < 0) {
            throw new IndexOutOfBoundsException();
        }
        T temp = array.get(i);
        array.set(i, array.get(j));
        array.set(j, temp);
    }

    public <E extends T> void copy(DynamicArray<E> c) {
        for (int i = 0; i < c.size; i++) {
            add(c.get(i));
        }
    }

    public void copyTo(DynamicArray<? super T> dest)
    {
        for (int i = 0; i < size; i++) {
            dest.add(this.get(i));//这个是将自己的复制到目标dest里面，super定义了下限
        }
    }
}
